package com.suning.sawp.service.impl.caller;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.suning.sawp.dto.caller.CallerInfo;
import com.suning.sawp.intf.caller.CallerService;
import com.suning.sawp.intf.esb.ShopFrequencyService;
import com.suning.vgs.follow.remote.intf.StoreConsumerService;
import com.suning.vgs.follow.remote.store.CallerInfoDto;

@Service("callerService")
public class CallerServiceImpl implements CallerService {

	private static final Logger LOGGER = LoggerFactory.getLogger(CallerServiceImpl.class);

	private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm";

	/**
	 * 默认是苏宁用户
	 */
	private static final String DEFAULT_NICKNAME = "苏宁用户";

	@Autowired
	StoreConsumerService storeConsumerService;

	@Autowired
	ShopFrequencyService shopFrequencyService;

	@Override
	public CallerInfo queryCallerInfo(String staffId, String phoneNo) {

		if (StringUtils.isBlank(staffId) || StringUtils.isBlank(phoneNo)) {
			throw new IllegalArgumentException("staffId||phoneNo can not be null!");
		}
		CallerInfo callerInfo = new CallerInfo();
		CallerInfoDto callerInfDto = storeConsumerService.queryCallerInfo(staffId, phoneNo);
		if (null != callerInfDto) {
			BeanUtils.copyProperties(callerInfDto, callerInfo, new String[] { "behaviorTime" });
			if (!callerInfDto.getIsStoreMan()) {
				// 时间格式转换
				callerInfo.setBehaviorTime(DateFormatUtils.format(callerInfDto.getBehaviorTime(), DATE_FORMAT));
				// 昵称没有设置默认值
				if (StringUtils.isBlank(callerInfo.getNickname())) {
					callerInfo.setNickname(DEFAULT_NICKNAME);
				}
				// 是会员 查询首复购状态
				String custNo = callerInfDto.getCustNo();
				Map<String, String> resultMap = shopFrequencyService.queryShopFrequency(Lists.newArrayList(custNo));
				if (null != resultMap && StringUtils.isNotBlank(resultMap.get(custNo))) {
					callerInfo.setDealTypeTxt(convertSFGTypeToDes(resultMap.get(custNo)));
				}
			}
		}
		return callerInfo;
	}

	/**
	 * 
	 * 功能描述: <br>
	 * 转换首复购状态到描述
	 *
	 * @param type
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	private String convertSFGTypeToDes(String type) {
		String text = "未购物";
		try {
			int intType = Integer.parseInt(type);
			if (intType > 1) {
				text = "已复购";
			}
			if (intType == 1) {
				text = "已首购";
			}
		} catch (NumberFormatException e) {
			LOGGER.error("来电显示，首复购状态转换异常！", e);
		}
		return text;

	}

}
